import React, { useState } from 'react';
import { Table, Radio, Button, Popconfirm, message } from 'antd';
import { useRequest } from '@/hooks';
import { fetchCheckOfficeGoods, fetchEmployeeAssets } from '@/pages/EntryManage/services';
import { WELCOME_NEW_EMPLOYEE } from './constants';
import styles from './index.less';

/**
 * 确认资产
 * @param {Function} onJumpToStep
 * @param {Function} onFinishedStep
 */
const CheckOfficeGoods = ({ onJumpToStep, onFinishedStep }) => {
    const [officeGoods, setOfficeGoods] = useState([]);
    const user = JSON.parse(localStorage.getItem('user') || '{}');
    const { employeeCode } = user;
    const [visible, setVisible] = useState(false);

    const initialOfficeGoods = originOfficeGoods => {
        let confirmedOfficeGoodsId = [];
        try {
            confirmedOfficeGoodsId = JSON.parse(localStorage.getItem('officeGoods'));
            if (!Array.isArray(confirmedOfficeGoodsId)) {
                confirmedOfficeGoodsId = [];
            }
        } catch (error) {
            confirmedOfficeGoodsId = [];
        }
        const result = originOfficeGoods.map(item => ({
            ...item,
            received: confirmedOfficeGoodsId.find(o => o.id === item.id)?.received
        }));
        setOfficeGoods(result);
    };

    const { loading: employeeAssetsLoading } = useRequest(fetchEmployeeAssets, {
        onSuccess: result => {
            const { code, data = [], msg } = result;
            if (code === 10000) {
                initialOfficeGoods(data);
            } else {
                message.error(msg);
            }
        }
    });

    // 员工确定接收资产
    const { run: runCheckOfficeGoods, loading: checkOfficeGoodsLoading } = useRequest(
        params => fetchCheckOfficeGoods(params),
        {
            manual: true
        }
    );

    const handleChange = (value, row) => {
        const result = officeGoods.map(item => {
            if (item.id === row.id) {
                return {
                    ...item,
                    received: value
                };
            }
            return item;
        });
        setOfficeGoods(result);
    };

    const columns = [
        {
            title: '名称',
            dataIndex: 'assetName'
        },
        {
            title: '资产类型',
            dataIndex: 'assetType',
            render: text => text !== '' && <span>{text === 0 ? '固定资产' : '消耗品'}</span>
        },
        {
            title: '资产编号',
            dataIndex: 'assetNumber',
            render: text => text || '-'
        },
        {
            title: '数量',
            dataIndex: 'required',
            width: 100,
            render: text => <span>{text ?? '-'}</span>
        },
        {
            title: '已接收',
            dataIndex: 'received',
            width: 150,
            render: (text, row) => (
                <Radio.Group value={text} onChange={e => handleChange(e.target.value, row)}>
                    <Radio value>是</Radio>
                    <Radio value={false}>否</Radio>
                </Radio.Group>
            )
        }
    ];

    // 点击上一步记录已选择资产
    const handleJumpToPrevStep = () => {
        const result = officeGoods.map(item => {
            const { id, received } = item;
            return { id, received };
        });
        localStorage.setItem('officeGoods', JSON.stringify(result));
        onJumpToStep(WELCOME_NEW_EMPLOYEE);
    };

    const handleClick = () => {
        const commitOfficeGoodCounts = officeGoods.filter(item => item.received === undefined);
        if (commitOfficeGoodCounts.length) {
            message.error('请确认如下资产您是否已接收到');
        } else {
            setVisible(true);
        }
    };

    return (
        <div className={styles.checkOfficeGoodsWrapper}>
            <p>已为你发放了如下资产，请确认是否已全部收到，如有遗漏，请联系人力行政部-行政专员</p>
            <Table
                rowKey="id"
                bordered
                columns={columns}
                dataSource={officeGoods}
                pagination={false}
                size="small"
                className={styles.contentTable}
            />
            <footer className={styles.checkOfficeFooterButton}>
                <Button type="gost" onClick={handleJumpToPrevStep} size="large">
                    上一步
                </Button>
                <Popconfirm
                    title="我已确认上述资产接收信息属实"
                    visible={visible}
                    onCancel={() => setVisible(false)}
                    onConfirm={async () => {
                        const confirmedOfficeGoodsId = officeGoods.map(item => {
                            if (item.received) {
                                return item.id;
                            }
                            return null;
                        });

                        const { code, msg } = await runCheckOfficeGoods({
                            employeeCode,
                            ids: confirmedOfficeGoodsId.filter(Boolean)
                        });

                        if (code === 10000) {
                            setVisible(false);
                            message.success(msg);
                            if (onFinishedStep) {
                                onFinishedStep();
                            }
                        } else {
                            message.error(msg);
                        }
                        return null;
                    }}
                >
                    <Button
                        disabled={checkOfficeGoodsLoading || employeeAssetsLoading}
                        type="primary"
                        size="large"
                        onClick={handleClick}
                    >
                        完善个人信息
                    </Button>
                </Popconfirm>
            </footer>
        </div>
    );
};

export default CheckOfficeGoods;
